from db import models
from lib import common
from TcpServer import user_data


def register(conn, back_dic):
	# 先根据用户名查是否有相应的数据
	user_list = models.User.select(name=back_dic['name'])
	# 如果用户不存在，就要在数据库中插入
	if not user_list:
		user = models.User(name=back_dic['name'], password=back_dic['password'], is_vip=0, is_locked=0, user_type=back_dic['user_type'], register_time=common.get_time())
		user.save()
		back_dic = {'flag': True, 'msg': "注册成功"}
		common.send_msg(conn, back_dic)
	# 存在就返回已存在
	else:
		# user_obj = user_data[0]
		# if user_obj.user_type == back_dic['user_type']:
		send_dic = {'flag': False, 'msg': '当前用户名已存在...'}
		common.send_msg(conn, send_dic)


def login(conn, back_dic):
	user_list = models.User.select(name=back_dic['name'])
	if not user_list:
		send_dic = {'flag': False, 'msg': '当前用户还未注册...'}
		common.send_msg(conn, send_dic)
	else:
		user_obj = user_list[0]
		if user_obj['password'] == back_dic['password']:
			send_dic = {'flag': True, 'msg': '登陆成功...'}
			session = common.get_session(back_dic['name'])
			send_dic['session'] = session
			# 将session中添加唯一标示的用户ID
			user_data.mutex.acquire()
			user_data.alive_user[back_dic['address']] = [session, user_obj.id]
			user_data.mutex.release()
		else:
			send_dic = {'flag': False, 'msg': '用户名或密码错误...'}
		common.send_msg(conn, send_dic)

